<template>
  <div class="video-container">
    <div class="video-controls">
      <h2>视频流：H264</h2>
      <BackButton />
    </div>
    <video ref="videoPlayer" controls autoplay muted></video>
  </div>
</template>

<script>
import BackButton from '../components/BackButton.vue'
import JMuxer from 'jmuxer';

export default {
  name: 'videoViewH264',
  components:{
    BackButton
  },
  data() {
    return {
      ws: null,
      jmuxer: null
    };
  },
  mounted() {
    this.initPlayer();
    this.connect();
  },
  beforeUnmount() {
    this.disconnect();
  },
  beforeRouteLeave(to, from, next) {
    this.disconnect();
    next()
  },
  methods: {
    initPlayer(){
      this.jmuxer = new JMuxer({
        node: this.$refs.videoPlayer,
        mode: 'video',
        flushingTime: 0,
        fps: 30,
        debug: false
      });
    },
    connect() {
      this.ws = new WebSocket('ws://127.0.0.1:8098/video/gkd');
      
      this.ws.binaryType = 'arraybuffer';
      
      this.ws.onopen = () => {
        console.log('WebSocket connected');
      };
      
      this.ws.onmessage = (event) => {
        if(this.jmuxer){
          //将接收到的h264数据传递给JMuxer进行解码播放
          this.jmuxer.feed({
            video:new Uint8Array(event.data)
          })
        }
      };
      
      this.ws.onerror = (error) => {
        console.error('WebSocket error:', error);
      };
      
      this.ws.onclose = () => {
        console.log('WebSocket disconnected');
      };
    },
    disconnect() {
      if (this.ws) {
        this.ws.close();
      }
      if(this.jmuxer){
        this.jmuxer.destroy();
      }
    },
  }
};
</script>

<style scoped>
.video-container {
  width: 90%;
  margin: 20px;
  text-align: center;
}

.video-controls {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-right: 20px;
}

.video-frame {
  width: 100%;
  max-width: 100%;
  max-height: 80vh;
  aspect-ratio: 16/9; /* 保持16:9比例 */
  background-color: #000;
  border: 1px solid #ddd;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
video {
  width: 100%;
  max-width: 100%;
  max-height: 80vh;
  background-color: #000;
}
</style>